/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.modules.deploy.domain.DpServer;

import com.alien.admin.modules.deploy.domain.DpServerConfig;
import com.alien.admin.modules.deploy.repository.DpServerConfigRepository;
import com.alien.admin.modules.deploy.service.DpServerConfigService;
import com.alien.admin.modules.utils.YamlBusinessService;
import com.alien.admin.modules.utils.YamlCicdTool;
import com.alien.admin.utils.*;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.DpServerRepository;
import com.alien.admin.modules.deploy.service.DpServerService;
import com.alien.admin.modules.deploy.service.dto.DpServerDto;
import com.alien.admin.modules.deploy.service.dto.DpServerQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.DpServerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zengzhifang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-09
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class DpServerServiceImpl implements DpServerService {

    private final DpServerRepository dpServerRepository;
    private final DpServerMapper dpServerMapper;

    private final DpServerConfigRepository dpServerConfigRepository;
    private final DpServerConfigService dpServerConfigService;

    @Override
    public Map<String, Object> queryAll(DpServerQueryCriteria criteria, Pageable pageable) {
        Page<DpServer> page = dpServerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(dpServerMapper::toDto));
    }

    @Override
    public List<DpServerDto> queryAll(DpServerQueryCriteria criteria) {
        return dpServerMapper.toDto(dpServerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public DpServerDto findById(Long projectId) {
        DpServer dpServer = dpServerRepository.findById(projectId).orElseGet(DpServer::new);
        ValidationUtil.isNull(dpServer.getProjectId(), "DpServer", "projectId", projectId);
        return dpServerMapper.toDto(dpServer);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DpServerDto create(DpServer resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setProjectId(snowflake.nextId());
        return dpServerMapper.toDto(dpServerRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DpServer resources) {
        DpServer dpServer = dpServerRepository.findById(resources.getProjectId()).orElseGet(DpServer::new);
        ValidationUtil.isNull(dpServer.getProjectId(), "DpServer", "id", resources.getProjectId());
        dpServer.copy(resources);
        dpServerRepository.save(dpServer);
        // 检测各个环境的DpServerConfig的buildParam是否有值。
        processDpServerConfig(resources, "debug");
        processDpServerConfig(resources, "test");
    }

    /**
     * 检查某个环境下DpServerConfig的BuildParam属性是否有值。
     *
     * @param resources
     * @param env
     */
    public void processDpServerConfig(DpServer resources, String env) {
        DpServerConfig dpServerConfig = dpServerConfigRepository.findFirstByProjectIdAndEnv(resources.getProjectId().intValue(), env);
        if (dpServerConfig == null || dpServerConfig.getId() == null) {
            log.info("dpServerConfigIsNull. projectId:{}, env:{}", resources.getProjectId(), env);
            return;
        }
        if (StringUtils.isNotBlank(dpServerConfig.getBuildParam())) {
            log.info("BuildParamIsNotBlank. projectId:{}, env:{}", resources.getProjectId(), env);
            return;
        }
        String buildParamJsonStr = YamlBusinessService.getBuildParamJsonStr(resources.getCodeType(), resources.getName(), env);
        if (StringUtils.isNotBlank(buildParamJsonStr)) {
            dpServerConfig.setBuildParam(buildParamJsonStr);
            dpServerConfig.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            dpServerConfigRepository.saveAndFlush(dpServerConfig);
        } else {
            log.info("buildParamJsonStr is blank");
        }
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long projectId : ids) {
            dpServerRepository.deleteById(projectId);
        }
    }

    @Override
    public void download(List<DpServerDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DpServerDto dpServer : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("项目名称", dpServer.getName());
            map.put("代码类型", dpServer.getCodeType());
            map.put("项目描述", dpServer.getDescription());
            map.put("仓库http地址", dpServer.getHttpUrl());
            map.put("仓库ssh地址", dpServer.getSshUrl());
            map.put("创建日期", dpServer.getCreateTime());
            map.put("更新时间", dpServer.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}